<?php

namespace app\common\model;

class AppConfig extends Base
{


    private string $dictKey = 'config_name';

    public function getById(string $app_id): array
    {
        $where = [['app_id' => $app_id]];
        $list = $this->where($where)->select()->toArray();
        return array_dict($list, $this->dictKey);
    }

    public function getByIdAndType(string $app_id, string $config_type): array
    {
        $where = [['app_id', '=', $app_id], ['config_type', '=', $config_type]];
        $list = $this->where($where)->select()->toArray();
        return $this->formatConfig($list);
    }

    public function getByIdAndTypeWithPublic(string $app_id, string $config_type): array
    {
        $where = [['app_id', '=', $app_id], ['config_type', '=', $config_type], ['config_purview', '=', 20]];
        $list = $this->where($where)->select()->toArray();
        return $this->formatConfig($list);
    }

    public function getValueByIdAndTypeWithName(string $app_id, string $config_type, string $name): string
    {
        $where = [['app_id', '=', $app_id], ['config_type', '=', $config_type], ['config_name', '=', $name]];
        $config = $this->where($where)->find();
        return $config ? $config['config_value'] : '';
    }

    /**
     * listValueToArray
     * @param $value
     * @return array|mixed
     */
    public function listValueToArray($value)
    {
        if (!$value) {
            return [];
        }
        $jsonArray = json_decode($value, true);
        if (!$jsonArray) {
            return [];
        }
        return $jsonArray;
    }

    /**
     * formatConfig
     * @param $allConfig
     * @return array
     */
    private function formatConfig($allConfig): array
    {
        $newConfig = [];
        foreach ($allConfig as $key => $val) {
            if ($val['config_value_type'] == 'list') {
                $val['config_value'] = $this->listValueToArray($val['config_value']);
            }
            $newConfig[$val['config_name']] = $val['config_value'];
        }
        return $newConfig;
    }
}